<template>
    <div class="role-add">
        <!-- 新增弹窗 -->
        <cvue-dialog :dialogVisible="dialogVisible"
            :dialogLoading="dialogLoading"
            title="新增"
            dialogWidth="550px"
            @handleOpen="getDetail"
            @closeDialog="closeDialog"
            @confirmDialog="confirmDialog"
            @handleClose="handleClose">
            <div class="dialog-body" slot="dialogBody">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="角色名称" prop="roleName">
                                <el-input maxlength="10" v-model.trim="ruleForm.roleName" placeholder="请输入角色名称，1-10个字符"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="角色描述" prop="describe">
                                <el-input maxlength="100" placeholder="请输入角色描述" v-model.trim="ruleForm.describe"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="页面权限" prop="authority">
                                <cvue-tree-grid :option="option">
                                    <template slot-scope="scope" slot="edit">
                                        <template v-if="scope.row.code == 20010 || scope.row.code == 20020">
                                            <el-checkbox disabled></el-checkbox>
                                        </template>
                                        <template v-else>
                                            <el-checkbox v-model="scope.row.edit" v-if="checkScope(scope.row)" @change="editChange(scope.row)"></el-checkbox>
                                        </template>
                                    </template>
                                    <template slot-scope="scope" slot="view">
                                        <template>
                                            <el-checkbox v-model="scope.row.view" v-if="checkScope(scope.row)" @change="viewChange(scope.row)"></el-checkbox>
                                        </template>
                                    </template>
                                </cvue-tree-grid>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </cvue-dialog>
    </div>
</template>
<script>
import cvueTreeGrid from '@/components/cvue-tree-grid'
import cvueDialog from '@/components/cvue-dialog'
import cvueTable from '@/components/cvue-table'
import {validPhone, validIp} from '@/util/validator.js'
export default {
    name: 'roleAdd',
    components: {
        cvueDialog,
        cvueTable,
        cvueTreeGrid
    },
    data () {
        var validUserName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入角色名称'))
            } else if (value === undefined) {
                callback(new Error('请输入角色名称'))
            } else if (value.length < 1 || value.length > 10) {
                callback(new Error('长度在 1 到 10 个字符'))
            } else {
                this.$store.dispatch('system/CheckSysroles', {roleName: value}).then((res) => {
                    if (!res.data) {
                        callback(new Error('角色名称已经存在'))
                    } else {
                        callback()
                    }
                })
            }
        }
        return {
            ruleForm: {
                roleName: '',
                describe: ''
            },
            rules: {
                roleName: [
                    { required: true, trigger: 'blur', validator: validUserName }
                    // { required: true, message: '请输入角色名称', trigger: 'blur' },
                    // { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
                ],
                describe: [
                    {min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur'}
                ]
            },
            disabled: true,
            dialogLoading: false,
            tableOption: {
                stripe: true,
                width: '100%',
                border: true,
                index: false,
                cloumn: [
                    {prop: 'describe', label: '模块', align: 'center'},
                    {prop: 'edit', label: '编辑权限', align: 'center', slotStatus: true},
                    {prop: 'view', label: '查看权限', align: 'center', slotStatus: true}
                ]
            },
            tableData: [
                // {
                //   code: '运营报表', edit: false, view: true
                // }
            ],
            option: {
                expandAll: true,
                columns: [
                    {
                        text: '模块',
                        value: 'describe',
                        width: 200
                    },
                    {
                        text: '编辑权限',
                        value: 'edit',
                        slotStatus: true,
                        align: 'center'
                    },
                    {
                        text: '查看权限',
                        value: 'view',
                        slotStatus: true,
                        align: 'center'
                    }
                ],
                data: [
                ]
            }
        }
    },
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        }
    },
    mounted () {
    },
    methods: {
        editChange (row) {
            console.log('editChange', row, this.option)
            // 判断是否是首页，不是则edit控制住view
            if (row.code == 21000) {
                this.option.data.forEach(ele => {
                    if (row.edit) {
                        this.$set(ele, 'view', true)
                        this.$set(ele, 'edit', true)
                        if (ele.children.length > 0) {
                            ele.children.forEach(child => {
                                if (child.code != 20010 && child.code != 20020) {
                                    this.$set(child, 'view', true)
                                    this.$set(child, 'edit', true)
                                } else {
                                    this.$set(child, 'view', true)
                                }
                            })
                        }
                    } else {
                        this.$set(ele, 'edit', false)
                        if (ele.children.length > 0 && ele.code != 20000) {
                            ele.children.forEach(child => {
                                this.$set(child, 'edit', false)
                            })
                        }
                    }
                })
            } else {
                if (!row.edit) {
                    this.option.data.forEach(ele => {
                        if (ele.code == 21000) {
                            this.$set(ele, 'edit', false)
                        }
                    })
                } else {
                    this.$set(row, 'view', true)
                    // 判断edit是否全选
                    var check = true
                    this.$nextTick(() => {
                        this.option.data.forEach(ele => {
                            // if (ele.code != 11000 && ele.code != 20000 && ele.code != 21000) {
                            if (ele.code != 20000 && ele.code != 21000) {
                                if (ele.children.length > 0) {
                                    ele.children.forEach(child => {
                                        if (!child.edit) {
                                            check = false
                                        }
                                    })
                                } else {
                                    if (!ele.edit) {
                                        check = false
                                    }
                                }
                            }
                        })
                        if (check) {
                            this.option.data.forEach(ele => {
                                if (ele.code == 21000) {
                                    this.$set(ele, 'edit', true)
                                }
                            })
                        }
                    })
                    // 联动的判断view是否全选
                    var check1 = true
                    this.$nextTick(() => {
                        this.option.data.forEach(ele => {
                            // if (ele.code != 11000 && ele.code != 21000) {
                            if (ele.code != 21000) {
                                if (ele.children.length > 0) {
                                    ele.children.forEach(child => {
                                        if (!child.view) {
                                            check1 = false
                                        }
                                    })
                                } else {
                                    if (!ele.view) {
                                        check1 = false
                                    }
                                }
                            }
                        })
                        if (check1) {
                            this.option.data.forEach(ele => {
                                if (ele.code == 21000) {
                                    this.$set(ele, 'view', true)
                                }
                            })
                        }
                    })
                }
            }
        },
        viewChange (row) {
            console.log('viewChange', row, this.option)
            if (row.code == 21000) {
                this.option.data.forEach(ele => {
                    if (row.view) {
                        // this.$set(ele, 'edit', true)
                        this.$set(ele, 'view', true)
                        if (ele.children.length > 0) {
                            ele.children.forEach(child => {
                                this.$set(child, 'view', true)
                            })
                        }
                    } else {
                        this.$set(ele, 'edit', false)
                        this.$set(ele, 'view', false)
                        if (ele.children.length > 0) {
                            ele.children.forEach(child => {
                                this.$set(child, 'edit', false)
                                this.$set(child, 'view', false)
                            })
                        }
                    }
                })
            } else {
                if (!row.view) {
                    this.$set(row, 'edit', false)
                    this.option.data.forEach(ele => {
                        if (ele.code == 21000) {
                            this.$set(ele, 'view', false)
                            this.$set(ele, 'edit', false)
                        }
                    })
                } else {
                    // 检测查看权限是否全选
                    this.$set(row, 'view', true)
                    var check = true
                    this.$nextTick(() => {
                        this.option.data.forEach(ele => {
                            // if (ele.code != 11000 && ele.code != 21000) {
                            if (ele.code != 21000) {
                                if (ele.children.length > 0) {
                                    ele.children.forEach(child => {
                                        if (!child.view) {
                                            check = false
                                        }
                                    })
                                } else {
                                    if (!ele.view) {
                                        check = false
                                    }
                                }
                            }
                            console.log(check)
                        })
                        console.log(1, check)
                        if (check) {
                            this.option.data.forEach(ele => {
                                if (ele.code == 21000) {
                                    this.$set(ele, 'view', true)
                                }
                            })
                        }
                    })
                }
            }
        },
        // 是否显示父级互选框
        checkScope (row) {
            if (row.children && row.children.length === 0) {
                return true
            } else {
                return false
            }
        },
        // 触发事件
        handleClose () {
            this.$refs['ruleForm'].clearValidate()
            // this.$refs['ruleForm'].resetFields()
            this.$emit('handleClose')
        },
        closeDialog () {
            this.$refs['ruleForm'].clearValidate()
            // this.$refs['ruleForm'].resetFields()
            this.$emit('closeDialog')
        },
        confirmDialog () {
            // 扁平化树数组
            function mapData (arr) {
                var newArr = []
                arr.map((item) => {
                    var arr = []
                    if (item.view) {
                        arr.push('view')
                    }
                    if (item.edit) {
                        arr.push('edit')
                    }
                    var permissions = arr.join(',')
                    if (item.children && item.children.length > 0) {
                        newArr.push({
                            code: item.code,
                            permissions: ''
                        })
                        newArr = newArr.concat(mapData(item.children))
                    } else {
                        newArr.push({
                            code: item.code,
                            permissions: permissions
                        })
                    }
                })
                return newArr
            }
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    var authority = mapData(this.option.data)
                    var newAuthority = []
                    authority.forEach((item, index) => {
                        if (item.code != 21000) {
                            if (item.permissions != '') {
                                newAuthority.push(item)
                            }
                        }
                    })
                    var params = {
                        roleName: this.ruleForm.roleName,
                        describe: this.ruleForm.describe,
                        authority: newAuthority
                    }
                    // console.log(newAuthority)
                    // return
                    params.roleId = this.$parent.roleId
                    this.dialogLoading = true
                    this.$store.dispatch('system/AddSysroles', params).then(res => {
                        // console.log(res)
                        if (res.code == 200) {
                            this.$message({
                                message: res.msg,
                                duration: 2000,
                                type: 'success'
                            })
                            this.$refs['ruleForm'].clearValidate()
                            this.$emit('confirmDialog')
                        } else {
                            this.$message({
                                message: res.msg,
                                duration: 2000,
                                type: 'error'
                            })
                            this.dialogLoading = false
                        }
                    }).catch(err => {
                        console.log(err)
                        this.dialogLoading = false
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        // 初始化弹窗
        getDetail () {
            this.option.data = []
            this.dialogLoading = false
            this.ruleForm = {
                roleName: '',
                describe: ''
            }
            // 获取权限列表
            this.$store.dispatch('user/GetAuthority').then((res) => {
                // console.log(res)
                if (res.code == 200) {
                    res.data.unshift({
                        code: '21000',
                        describe: '全选',
                        remarks: '',
                        children: [],
                        pcode: '0'
                    })
                    this.option.data = res.data
                    this.option.data.forEach((item, index) => {
                        if (item.children && item.children.length > 0) {
                            item.children.forEach((child, i) => {
                                this.$set(item.children[i], 'edit', false)
                                this.$set(item.children[i], 'view', false)
                            })
                        } else {
                            this.$set(item, 'edit', false)
                            this.$set(item, 'view', false)
                        }
                    })
                }
            })
        }
    }
}
</script>
<style scoped lang="scss">
.role-add{
    .dialog-body{
        height: 400px;
        overflow: auto;
    }
}
</style>
